<?php

/**
 * home actions.
 *
 * @package    coverd
 * @subpackage home
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class homeActions extends sfActions
{
    public function executeIndex(sfWebRequest $request)
    {
        // Logged in users should go directly to their portal page
        if ($this->getUser()->isAuthenticated()) {
            $this->redirect("feedback/index");
            return;
        }

        if (isset($_SERVER["SCRIPT_NAME"])) {
            $symfonyUri = str_replace($_SERVER["SCRIPT_NAME"], "", $_SERVER["REQUEST_URI"]);
        }
        else {
            $symfonyUri = $_SERVER["REQUEST_URI"];
        }

        // Strip the leading slash
        $symfonyUri = ltrim($symfonyUri, "/");

        // If we got to this page from a redirect because the user isn't logged in
        if ($symfonyUri != "/") {
            $this->redirectUri = $symfonyUri;
        }
    }

    protected function doLogin($user) {
        $user->setLastLoginDate(date("Y-m-d H:i:s"));
        $user->save();

        $this->getUser()->setAuthenticated(true);
        $this->getUser()->setAttribute("id", $user->getId());
    }

    public function executeDoLogin(sfWebRequest $request)
    {
        $email = $request->getParameter("email", null);
        $password = $request->getParameter("password", null);
        if ($email && $password) {

            $users = Doctrine_Core::getTable("User")
                ->createQuery("u")
                ->where("u.email = ?", $email)
                ->andWhere("u.password = ?", md5($password))
                ->limit(1)
                ->execute();
            if ($users && $users->count() == 1) {
                if ($users[0]->getActive()) {
                    $this->doLogin($users[0]);

                    $redirectUri = $request->getParameter("redirect-uri", null);
                    if ($redirectUri) {
                        $this->redirect($redirectUri);
                    }
                    else {
                        $this->redirect("feedback/index");
                    }
                }
                else {
                    $this->getUser()->setFlash("loginError", "User not yet activated. Please see your activation email or contact support.");
                }
            }
            else {
                $this->getUser()->setFlash("loginError", "Username or password not found. Please try again.");
            }
        }
        else {
            $this->getUser()->setFlash("loginError", "Login failed. Please try again.");
        }

        $this->getUser()->setFlash("loginEmailAttempt", $email);

        $this->redirect("home/index");
    }

    public function executeDoLogout(sfWebRequest $request)
    {
        $this->getUser()->setAuthenticated(false);
        $this->getUser()->setAttribute("id", null);

        $this->redirect("home/index");
    }

    public function executeRegister(sfWebRequest $request)
    {
        // Nothing...?
    }

    public function executeDoRegister(sfWebRequest $request)
    {
        $this->errorField = "";
        $this->errorDescription = "";

        $this->email = $request->getParameter("email", null);
        if ($this->email && preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $this->email)) {

            // Check the user doesn't already exist
            $emailFound = Doctrine_Core::getTable("User")
                ->createQuery("u")
                ->where("u.email = ?", $this->email)
                ->count();
            if ($emailFound == 0) {
                $this->password = $request->getParameter("password", null);
                if ($this->password) {
                    if (strlen($this->password) >= 8) {
                        $confirmPassword = $request->getParameter("confirm-password", null);
                        if ($this->password == $confirmPassword) {

                            // OK, we're actually ready to create. Check the return value
                            if (!User::create($this->email, $this->password, $this->getController()->genUrl("home/activate"))) {
                                $this->errorField = "other";
                                $this->errorDescription = "Sorry, could not create user at this time. Please try again later.";
                            }

                        }
                        else {
                            $this->errorField = "confirm-password";
                            $this->errorDescription = "Please ensure passwords match";
                        }
                    }
                    else {
                        $this->errorField = "password";
                        $this->errorDescription = "Please ensure passwords are at least 8 characters long";
                    }
                }
                else {
                    $this->errorField = "password";
                    $this->errorDescription = "Please enter a valid password";
                }
            }
            else {
                $this->errorField = "email";
                $this->errorDescription = "There is already an account with this email address.";
            }
        }
        else {
            $this->errorField = "email";
            $this->errorDescription = "Please enter a valid email address";
        }

        if ($this->errorField) {
            $this->setTemplate("register");
        }
        else {
            $this->setTemplate("registerComplete");
        }
    }

    public function executeActivate(sfWebRequest $request)
    {
        $this->success = false;
        $this->errorMessage = "";

        $hash = $request->getParameter("hash", null);
        if ($hash) {
            $users = Doctrine_Core::getTable("User")
                ->createQuery("u")
                ->where("u.activation_hash = ?", $hash)
                ->limit(1)
                ->execute();
            if ($users && $users->count() == 1) {
                if (!$users[0]->getActive()) {
                    $users[0]->setActive(true);
                    $users[0]->save();

                    $this->doLogin($users[0]);

                    $this->success = true;
                }
                else {
                    $this->errorMessage = "User has already been activated.";
                }
            }
            else {
                $this->errorMessage = "Invalid activation code.";
            }
        }
        else {
            $this->errorMessage = "Activation code not supplied.";
        }
    }

    public function executeHelp(sfWebRequest $request)
    {
        // Nothing...?
    }

    public function executeContact(sfWebRequest $request)
    {
        // Nothing...?
    }

    public function executeDoPasswordChange(sfWebRequest $request)
    {
        $this->passwordChangeAttempt = true;
        $this->errorField = "";
        $this->errorDescription = "";

        $this->userId = $this->getUser()->getAttribute("id");
        $user = Doctrine_Core::getTable("User")->find($this->userId);
        if ($user) {

            $this->currentPassword = $request->getParameter("current-password", null);
            if ($this->currentPassword) {

                if (md5($this->currentPassword) == $user->getPassword()) {

                    $this->newPassword = $request->getParameter("new-password", null);
                    if ($this->newPassword) {

                        if (strlen($this->newPassword) >= 8) {

                            $confirmNewPassword = $request->getParameter("confirm-new-password", null);
                            if ($this->newPassword == $confirmNewPassword) {

                                // OK, we're actually ready to do the update

                                $user->setPassword(md5($this->newPassword));
                                $user->save();
                            }
                            else {
                                $this->errorField = "confirm-password";
                                $this->errorDescription = "Please ensure passwords match";
                            }
                        }
                        else {
                            $this->errorField = "new-password";
                            $this->errorDescription = "Please ensure passwords are at least 8 characters long";
                        }
                    }
                    else {
                        $this->errorField = "new-password";
                        $this->errorDescription = "Please enter a valid new password";
                    }
                }
                else {
                    $this->errorField = "current-password";
                    $this->errorDescription = "The current password is incorrect";
                }
            }
            else {
                $this->errorField = "current-password";
                $this->errorDescription = "Please enter the current password";
            }
        }
        else {
            $this->errorField = "other";
            $this->errorDescription = "User is not logged in";
        }

        $this->getUser()->setFlash("passwordChangeAttempt", $this->passwordChangeAttempt);
        $this->getUser()->setFlash("errorField", $this->errorField);
        $this->getUser()->setFlash("errorDescription", $this->errorDescription);

        $this->redirect("feedback/setup#account");
    }

    public function executeError404(sfWebRequest $request)
    {
        // Nothing...?
    }

    public function executeGiveFeedback(sfWebRequest $request)
    {
        $this->setLayout(false);
        $this->setTemplate("genericJson");
        $this->success = false;

        $emailAddress = null;
        $userId = null;
        if ($this->getUser()) {
            $userId = $this->getUser()->getAttribute("id");
            if ($userId) {
                $user = Doctrine_Core::getTable("User")->find($userId);
                if ($user) {
                    $emailAddress = $user->getEmail();
                }
            }
        }

        $type = $request->getParameter("type");
        $message = $request->getParameter("message");
        if ($type && $message) {

            $content =
                "<div><strong>Feedback from:</strong> " . ($emailAddress ? $emailAddress . " (user ID " . $userId . ")" : "(unknown)") . "</div>"
                . "<div><strong>Type:</strong> " . $type . "</div>"
                . "<div><strong>Message:</strong> " . $message . "</div>";

            EmailHelper::send("cameron.ross@gmail.com", "New Fydal feedback", $content);

            $this->success = true;
        }
    }

    public function executeDoEmailSettingsChange(sfWebRequest $request)
    {
        $this->errorDescription = "";

        $this->userId = $this->getUser()->getAttribute("id");
        $user = Doctrine_Core::getTable("User")->find($this->userId);
        if ($user) {
            $newEmailFrequency = $request->getParameter("email-frequency", null);
            if (in_array($newEmailFrequency, array("never", "daily", "weekly"))) {

                if ($newEmailFrequency == "never") {
                    $user->setNewFeedbackEmailType("none");
                    $user->save();
                }
                else {
                    $user->setNewFeedbackEmailType($newEmailFrequency);
                    $user->setLastNewFeedbackEmailDate(date("Y-m-d H:i:s")); // Only email about feedback retrieved from now on
                    $user->save();
                }
            }
            else {
                $this->errorDescription = "Could not save email frequency type.";
            }
        }
        else {
            $this->errorDescription = "User is not logged in";
        }

        $this->getUser()->setFlash("emailSettingsChangeAttempt", true);
        $this->getUser()->setFlash("errorDescription", $this->errorDescription);

        $this->redirect("feedback/setup#account");
    }

    // Copied from feedback actions.class.php
    // TODO Share this code somehow
    protected function retreiveUserIdAndValidateSession()
    {
        $this->userId = $this->getUser()->getAttribute("id");

        $this->user = Doctrine_Core::getTable("User")->find($this->userId);
        $this->forward404Unless($this->user);

        $this->getResponse()->setSlot("loggedInUser", $this->user);
    }

    public function executeSubscribeComplete(sfWebRequest $request)
    {
        $this->retreiveUserIdAndValidateSession();

        // TODO Check response variables (?) to confirm that a payment was legit performed!!
        // TODO Otherwise what is to prevent users calling this page directly...?

        $accountType = $request->getParameter("type", null);
        if (in_array($accountType, array("premium", "premium-enterprise"))) {
            $this->user->setAccountType($accountType);
            $this->user->save();

            EmailHelper::send("cameron.ross@gmail.com", "New premium user", "The user with email " . $this->user->getEmail() . " upgraded to a " . $accountType . " account.");

            $this->accountType = $accountType;
        }
        else {
            $this->redirect("home/subscribeCancel");
        }
    }

    public function executeSubscribeCancel(sfWebRequest $request)
    {
        $this->retreiveUserIdAndValidateSession();
    }
}
